package com.buymobile.controller;
/**
 * 首页登录，及退出，其中有部分包含页面的映射。
 */
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.bind.support.SessionStatus;

import com.buymobile.domain.Company;
import com.buymobile.service.CompanyService;

@Controller
@RequestMapping("/index")
@SessionAttributes("company")
public class IndexController {
	
	private CompanyService companyService;
	
	@Autowired
	public void setCompanyService(CompanyService companyService) {
		this.companyService = companyService;
	}
	//登录
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public String login(@RequestParam String userName,@RequestParam String password,ModelMap model){
		
		Company company = companyService.getByUserName(userName);
		if(company!=null){
			if(company.getPassword().equals(password)){
				//密码正确
				 model.addAttribute("company",company);
				return "/manager/main";
			}else{
				//密码不正确,返回登录页面
				return "redirect:/";
			}
		}else{
			//为空，该用户不存在，返回登录页面
			return "redirect:/";
		}
	}
	
	//退出
	@RequestMapping(value="/logout")
	public String logout(SessionStatus status){
		status.setComplete();
		return "redirect:/";
	}
	
	//修改密码
	@RequestMapping(value="/changePassword")
	public String editPassword(){
		return "manager/editPassword";
	}
	@RequestMapping(value="/updatePassword")
	public String updatePassword(@RequestParam String id,@RequestParam String password,@RequestParam String newPassword, HttpServletResponse response) throws IOException{
		
		Company company = companyService.get(Integer.parseInt(id));
		String returnInfo = "";
		if(company.getPassword().equals(password)){
			company.setPassword(newPassword);
			companyService.update(company);
			returnInfo = "1";
		}else{
			returnInfo = "2";
		}
		response.setCharacterEncoding("UTF-8");
		response.setContentType("text/html"); 
		PrintWriter out = response.getWriter();
		out.write(returnInfo);
		out.flush();
		return null;
		
	}
	
	@RequestMapping(value="/top")
	public String top(){
		return "/manager/top";
	}
	@RequestMapping(value="/center")
	public String center(){
		return "/manager/center";
	}
	@RequestMapping(value="/down")
	public String down(){
		return "/manager/down";
	}
	@RequestMapping(value="/left")
	public String left(){
		return "/manager/left";
	}
	@RequestMapping(value="/right")
	public String right(){
		return "/manager/right";
	}
}
